<?php
/**
 * Script for manage reports
 */

// Include init script with functions and constants
include("init.php");

// Instance the Report class
$report = (object) new report();

// Get the action to perform
$action = getParam('action');

// Mode of action
$mode = getParam('mode');

//$id = getArrayVal($_GET, "id");

// Login validation
if ($action != "login" and $action != "logout" and $action != "resetpassword" and $action != "loginerror") {
    if (!isset($_SESSION["userid"])) {
        $template->assign("loginerror", 0);
        $template->display("login.tpl");
        die();
    }
}

// For system message
$template->assign("mode", $mode);

// Get the available languages
$languages = getAvailableLanguages();
$template->assign("languages", $languages);

// set css classes for menue buttons
$classes = array("overview" => "overview", "msgs" => "msgs", "tasks" => "tasks", "miles" => "miles", "files" => "files", "users" => "users_active", "tracker" => "tracking");
$mainclasses = array("desktop" => "", "reports" => "active", "profil" => "", "admin" => "");

// Assign classes to template
$template->assign("mainclasses", $mainclasses);
$template->assign("classes", $classes);

// Default action
if ( !$action) {
	
	// Page title
	$title = $langfile['reports'];
	
	// Get all companies
	$company = new company();
	//$companies = $company->getAllCompanies();
	$companies = $company->getHierarchyForSelect();
	unset($company);
	
	// Get projects
	$project = new project();
	$projects = $project->getProjectsForSelect(1);
	unset($project);
	
	// Get Milestones
	$milestone = new milestone();
	$milestones = $milestone->getAllMilestonesForSelect();
	unset($milestone);
	
	// Current day
	$current_day = date('Y-m-d');
	$next_day = date('Y-m-d', mktime(null, null, null, date('m'), date('d') + 1, date('Y')));
	
	// Reports
	$reports = $report->getAllReports();
	
	$template->assign("title", $title);
	$template->assign('companies', $companies);
	$template->assign('projects', $projects);
	$template->assign('milestones', $milestones);
	$template->assign('current_day', $current_day);
	$template->assign('next_day', $next_day);
	
	$template->assign('reports', $reports);
	
	$template->display('reportsindex.tpl');
	
}

// Generate Report Action
else if ( $action == 'generate' ) {
	
	// Data from form
	$name = $_POST['name'];
	$company_id = (int) $_POST['company_id'];
	$date = $_POST['date'];
	$date_end = ( isset( $_POST['date_range'] ) && (int) $_POST['date_range'] ) ? $_POST['date_end'] : null;
	$project_status = $_POST['project_status'];
	$project_id = ( $project_status == 'list' ) ? $_POST['project_id'] : null;
	$milestone_status = $_POST['milestone_status'];
	$milestone_id = ( $milestone_status == 'list' ) ? $_POST['milestone_id']: null;
	$project_files = ( isset($_POST['project_files']) && !empty($_POST['project_files']) ) ? true: false;
	
	// Pass arguments to the generate method of the report class
	$final_report = $report->generate($company_id, $date, $date_end, $project_status, $project_id, $milestone_status, $milestone_id, $project_files);
	
	// Criteria for report
	$template->assign('name', $name);
	$template->assign('company_id', $company_id);
	$template->assign('date', $date);
	$template->assign('date_end', $date_end);
	$template->assign('project_status', $project_status);
	$template->assign('project_id', $project_id);
	$template->assign('milestone_status', $milestone_status);
	$template->assign('milestone_id', $milestone_id);
	$template->assign('project_files', $project_files);
	
	// Format data for display in report
	
	$priorities = array(
			0 => $langfile['task_priority_critical'],
			1 => $langfile['task_priority_high'],
			2 => $langfile['task_priority_medium'],
			3 => $langfile['task_priority_low']
	);
	
	setlocale(LC_TIME , 'es_MX.utf8');
	foreach ( $final_report as $i => $project ) {
		$final_report[$i]['startstring'] = ucwords( strftime('%A, %e %B, %Y', $project['start']) );
		$final_report[$i]['endstring'] = ( $project['end'] == '0' || empty($project['end']) ) ? 'Sin finalizar' : ucwords( strftime('%A,%e %B, %Y', $project['end']) );
		$final_report[$i]['budget'] = '$' . @number_format($project['budget'], 2);
		
		if ( !empty($project['tasks']) ) {
			foreach ( $project['tasks'] as $t => $task ) {
				$final_report[$i]['tasks'][$t]['endstring'] = ucwords( strftime('%A,%e %B, %Y', $task['end']) );
				$priority = $task['priority'];
				$final_report[$i]['tasks'][$t]['prioritystring'] = $priorities[ $priority ];
			}
		}
		
	}
	
	$template->assign( 'title', $name );
	$template->assign( 'report_name', $name );
	$template->assign( 'show_save_option', true );
	$template->assign( 'report', $final_report );
	
	$template->display('reportshow.tpl');
	
}

// Save report
else if ( $action == "save" ) {
	
	// Data from form
	$name = getParam('name');
	$name = getParam('name');
	$company_id = (int) getParam('company_id');
	$date = getParam('date');
	$date_end = getParam('date_end');
	$project_status = getParam('project_status');
	$project_id = ( $project_status == 'list' ) ? getParam('project_id') : null;
	$milestone_status = getParam('milestone_status');
	$milestone_id = ( $milestone_status == 'list' ) ? getParam('milestone_id') : null;
	$project_files = ( getParam('project_files') ) ? true : false;
	
	// Pass arguments to the generate method of the report class
	$final_report = $report->generate($company_id, $date, $date_end, $project_status, $project_id, $milestone_status, $milestone_id, $project_files);
	
	// Empty report
	if ( empty($final_report) ) {
		$response = array( 'status' => false, 'msg' => $langfile['emptyreport'] );
		header('Content-type: application/json');
		echo json_encode($response);
		exit;
	}
	
	// Criteria to generate report
	$criteria = array(
		'name' => $name,
		'company_id' => $company_id,
		'date' => $date,
		'date_end' => $date_end,
		'project_status' => $project_status,
		'project_id' => $project_id,
		'milestone_status' => $milestone_status,
		'milestone_id' => $milestone_id,
		'project_files' => $project_files
	);
	
	// Save report in database
	$save_report_response = $report->save($name, $criteria, $final_report);
	
	if ( !$save_report_response ) {
		
		$response = array(
			'status' => false,
			'msg' => $langfile["save_error"]
		);
		
	} else {
		
		$response = array(
			'status' => true,
			'msg' => $langfile['save_success']
		);
		
	}
	
	header('Content-type: application/json');
	echo json_encode($response);
	
}

// View report
else if ( $action == 'view' ) {
	
	// Report ID
	$report_id = getParam('report_id');
	
	// Get report data
	$report_data = $report->getReport($report_id);
	
	$final_report = $report_data['report'];
	
	// Format data for display in report
	
	$priorities = array(
			0 => $langfile['task_priority_critical'],
			1 => $langfile['task_priority_high'],
			2 => $langfile['task_priority_medium'],
			3 => $langfile['task_priority_low']
	);
	
	setlocale(LC_TIME , 'es_MX.utf8');
	foreach ( $final_report as $i => $project ) {
		$final_report[$i]['startstring'] = ucwords( strftime('%A, %e %B, %Y', $project['start']) );
		$final_report[$i]['endstring'] = ( $project['end'] == '0' || empty($project['end']) ) ? 'Sin finalizar' : ucwords( strftime('%A,%e %B, %Y', $project['end']) );
	
		if ( !empty($project['tasks']) ) {
			foreach ( $project['tasks'] as $t => $task ) {
				$final_report[$i]['tasks'][$t]['endstring'] = ucwords( strftime('%A,%e %B, %Y', $task['end']) );
				$priority = $task['priority'];
				$final_report[$i]['tasks'][$t]['prioritystring'] = $priorities[ $priority ];
			}
		}
	
	}
	
	$report_name = $report_data['name'];
	$project_files = $report_data['criteria']['project_files'];
	
	$template->assign('project_files', $project_files);
	$template->assign('title', $report_data['name']);
	$template->assign('report', $final_report);
	$template->assign('report_name', $report_name);
	
	$template->display('reportshow.tpl');
	
}

// PDF view
else if ( $action == 'pdf' ) {
	
	// Report ID
	$report_id = getParam('report_id');
	
	$pdf_filename = 'reporte-' . $report_id . '.pdf';
	$pdf_file = CL_PDFREPORTS . '/' . $pdf_filename;
	
	// Check if PDF file is already generated
	if ( !file_exists($pdf_file) ) {
		
		set_time_limit(0);
		
		// Get report data
		$report_data = $report->getReport($report_id);
		
		$final_report = $report_data['report'];
		
		// Format data for display in report
		
		$priorities = array(
			0 => $langfile['task_priority_critical'],
			1 => $langfile['task_priority_high'],
			2 => $langfile['task_priority_medium'],
			3 => $langfile['task_priority_low']
		);
		
		setlocale(LC_TIME , 'es_MX.utf8');
		
		foreach ( $final_report as $i => $project ) {
			
			$final_report[$i]['startstring'] = ucwords( strftime('%A, %e %B, %Y', $project['start']) );
			$final_report[$i]['endstring'] = ( $project['end'] == '0' || empty($project['end']) ) ? 'Sin finalizar' : ucwords( strftime('%A,%e %B, %Y', $project['end']) );
		
			if ( !empty($project['tasks']) ) {
				foreach ( $project['tasks'] as $t => $task ) {
					$final_report[$i]['tasks'][$t]['endstring'] = ucwords( strftime('%A,%e %B, %Y', $task['end']) );
					$priority = $task['priority'];
					$final_report[$i]['tasks'][$t]['prioritystring'] = $priorities[ $priority ];
				}
			}
			
		}
		
		$report_name = $report_data['name'];
		$project_files = $report_data['criteria']['project_files'];
		
		$template->assign('project_files', $project_files);
		$template->assign('title', $report_data['name']);
		$template->assign('report', $final_report);
		$template->assign('report_name', $report_name);
		
		// Get raw HTML to put into PDF
		$html = $template->fetch('reportpdf.tpl');
		//$template->display('reportpdf.tpl');
		
		require_once 'include/dompdf/dompdf_config.inc.php';
		
		$dompdf = new DOMPDF();
		$dompdf->load_html($html, 'UTF-8');
		$dompdf->set_paper('a4', 'landscape');
		$dompdf->render();
		
		$pdf = $dompdf->output();
		
		$pathinfo = pathinfo($pdf_file);
		
		// Create PDF directory if not exists
		if ( !file_exists($pathinfo['dirname']) )
			mkdir($pathinfo['dirname']);
		
		$file_put_contents_response = file_put_contents($pdf_file, $pdf);
		
		if ( $file_put_contents_response === FALSE ) {
			header('Location: managereports.php?mode=reporterror');
			exit;
		}
		
	}
	
	header('Content-type: application/pdf');
	header('Content-Disposition: inline; filename="' . $pdf_filename . '"');
	header('Content-Transfer-Encoding: binary');
	header('Content-Length: ' . filesize($pdf_file));
	header('Accept-Ranges: bytes');
	
	readfile($pdf_file);
	
}

else if ( $action == "delete" ) {
	
	// Check for permissions for this user
	if ( !$userpermissions['reports']['del'] ) {
		
		$errtxt = $langfile["nopermission"];
		$noperm = $langfile["accessdenied"];
		
		$template->assign("errortext", "$errtxt<br>$noperm");
		$template->display("error.tpl");
		
		die();
		
	}
	
	$report_id = getParam('report_id');
	
	$pdf_filename = 'reporte-' . $report_id . '.pdf';
	$pdf_file = CL_PDFREPORTS . '/' . $pdf_filename;
	
	$pdf_deletion = ( file_exists($pdf_file) ) ? unlink($pdf_file) : true;
	
	if ( $pdf_deletion ) {
		
		$report_delete_response = $report->delete( $report_id );
		
		if ( $report_delete_response )
			header("Location: managereports.php?mode=reportdeleted");
		else
			header("Location: managereports.php?mode=reporterror");
		
	} else {
		header("Location: managereports.php?mode=reporterror");
	}
	
}

else if ($action == "loginerror") {
    $template->display("resetpassword.tpl");
} elseif ($action == "resetpassword") {
    $newpass = $user->resetPassword($email);
    if ($newpass != "") {
        // Send e-mail with new password
        $themail = new emailer($settings);
        $themail->send_mail($email, $langfile["projectpasswordsubject"], $langfile["hello"] . ",<br /><br/>" . $langfile["projectpasswordtext"] . "<br /><br />" . $langfile["newpass"] . ": " . "$newpass<br />" . $langfile["login"] . ": <a href = \"$url\">$url</a>");

        $template->assign("success", 1);
        $template->display("resetpassword.tpl");
    } else {
        $template->assign("loginerror", 1);
        $template->display("resetpassword.tpl");
    }
} elseif ($action == "login") {
    $mode = getArrayVal($_GET, "openid_mode");
    $username = getArrayVal($_POST, "username");
    $pass = getArrayVal($_POST, "pass");
    // normal login
    if ($user->login($username, $pass)) {
        $loc = $url . "index.php?mode=login";
        header("Location: $loc");
    } else {
        $template->assign("loginerror", 1);
        $template->display("login.tpl");
    }
} elseif ($action == "logout") {
    if ($user->logout()) {
        header("Location: index.php?mode=logout");
    }
}
